import pandas as pd
import numpy as np
import tushare as ts
import sklearn
from sklearn.preprocessing import scale    # 数据预处理: 标准化
from sklearn.svm import SVC

pd.set_option('display.max_columns', None)

# 获取指定上市代码的公司的K线交易信息
# 数据返回格式：index(['date', 'open', 'close', 'high', 'low', 'volume', 'code'], dtype='object')
k_data = ts.get_k_data('600848', start='1988-01-01', end='', ktype='D')  # 训练集数据

k_data['close_change'] = k_data['close'].pct_change()

k_data.dropna(inplace=True)  # 在原来数据集上删除NaN

# 定义训练的数据特征（核心是收盘价）
feature_data = pd.DataFrame()
feature_data['close'] = k_data['close']   # 取收盘价预测
feature_data['close_change'] = k_data['close_change']   # 股价涨跌，后面用来生成标签

# 特征工程：使用收盘价，连续一周作为一个特征训练输入
for i in range(1,8,1):
    feature_data['close-d' + str(i)] = k_data['close'].shift(i) # shift()函数代表数据往后移动

feature_data.dropna(inplace=True)   # 在原来数据集上删除

train_label = np.sign(feature_data['close_change'].shift(-1))
feature_data.drop(['close_change'], axis=1, inplace=True)

train_data = sklearn.preprocessing.scale(feature_data)  # 将给定数据进行标准化

train_label.replace(to_replace=np.NaN, value=0, inplace=True)

svc_classifier = SVC(kernel='rbf')

svc_classifier.fit(train_data, train_label)
svc_classifier.score(train_data, train_label)

predict = svc_classifier.predict(train_data)
correct_num = (predict == train_label).sum()
print(predict)
